package pixelwaks.ctrl.impl;

import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.swing.AbstractAction;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

import common.ctrl.IObserver;
import common.gui.IViewable;
import common.gui.impl.HelpDialog;
import common.i18n.ChangeLanguage;
import common.i18n.Language;
import common.util.MyClassLoader;

import pixelwaks.gui.impl.MainFrame;
import pixelwaks.gui.impl.Menu;

@SuppressWarnings("serial")
public class MenuCtrl extends AbstractAction implements IObserver {


	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private List<IViewable> observers = new ArrayList<IViewable>();
	@Override
	public void actionPerformed(ActionEvent e) {
		JMenuItem mnuFileNewGame = (JMenuItem) this.getValue("Menu.inewGame");
		JMenuItem[] mnuFileLanguageLanguages = new JMenuItem[Menu.NUMBER_OF_LANGUAGES];
		for(int i=0; i<Menu.NUMBER_OF_LANGUAGES; i++) {
			mnuFileLanguageLanguages[i] = (JMenuItem) this.getValue("Menu.ilanguage" + (i+1));
		}
		
		JMenuItem mnuFileExit = (JMenuItem) this.getValue("Menu.iexit");
		JMenuItem mnuHelpAbout = (JMenuItem) this.getValue("Menu.iabout");
		JMenuItem mnuHelpHelp = (JMenuItem) this.getValue("Menu.ihelp");
		
		if(e.getSource() == mnuFileExit) {
			System.exit(0);
		}
		else if(e.getSource() == mnuFileNewGame) {
			
			Object[] options = {"Hejsan", "Svejsan"};
			int chose = JOptionPane.showOptionDialog(null, "Do you want to start a new game?", 
					"New Game", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
			
			if(chose == 1) {
				updateView();
			}
		}
		else if(e.getSource() == mnuHelpAbout) {
			JOptionPane.showMessageDialog(null, "Lite om oss");
		}
		else if(e.getSource() == mnuHelpHelp) {
			new HelpDialog();
		}
		else {
			for(int i=0; i<Menu.NUMBER_OF_LANGUAGES; i++) {
        		if(e.getSource() == mnuFileLanguageLanguages[i]) {
        			ChangeLanguage.setLanguage(ResourceBundle.getBundle(
        					ChangeLanguage.LOCALIZE_BUNDLE + "_" + Language.langISO.get(i), Locale.getDefault(), MyClassLoader.getInstance()));
        		}
        	}
		}

	}

	@Override
	public void addView(IViewable iv) {
		observers.add(iv);

	}
	public void updateView() {

		for (IViewable view : observers) {
			System.out.println(view.getClass());
			if(view.getClass() == MainFrame.class) {
				System.out.println("update");
				view.updateView("new");
			}
		}
	}
}
